﻿using Cyss.Core;
using Microsoft.AspNetCore.Components;
using System.Diagnostics.CodeAnalysis;

namespace Cyss.TaskControl.Components
{
    public partial class RealTableCell<TItem> : ComponentBase, IDisposable
    {
        [Parameter]
        public IRealTableColumn Column { set; get; }

        [Parameter]
        [NotNull]
        public TItem? Item { set; get; }

        public object Value { set; get; }

        private bool IsValueChange { set; get; }


        protected override void OnInitialized()
        {
            if (typeof(TItem).IsImplementBaseType<RealTableViewModelBase>())
            {
                (Item as RealTableViewModelBase).PropertyChanged+=Item_PropertyChanged;
            }
            Value=typeof(TItem).GetProperty(Column.FileName).GetValue(Item);
            base.OnInitialized();
        }

        private void Item_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName==Column.FileName)
            {
                IsValueChange=true;
            }
        }

        protected override Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                Task.Run(async () =>
                {
                    while (true)
                    {
                        ValueChange();
                        await Task.Delay(100);
                    }
                });
            }
            return base.OnAfterRenderAsync(firstRender);
        }

        private async void ValueChange()
        {
            if (IsValueChange)
            {
                var value = Item?.GetType().GetProperty(Column.FileName).GetValue(Item);
                if (value!=Value)
                {
                    Value=value;
                    await InvokeAsync(StateHasChanged);
                    IsValueChange=false;
                }
            }
        }

        public void Dispose()
        {
            if (Item==null)
            {
                return;
            }
            if (!typeof(TItem).IsImplementBaseType<RealTableViewModelBase>())
            {
                return;
            }
            (Item as RealTableViewModelBase).PropertyChanged-=Item_PropertyChanged;
        }

        protected RenderFragment GetValue() => async builder =>
        {
            if (this.Column.Template != null)
            {
                builder.AddContent(0, this.Column.Template.Invoke(this.Item));
            }
            else
            {
                var content = Value;
                builder.AddContent(0, content);
            }
        };
    }

}
